
const { pool } = require('../dbop/mysql')
// connection.connect();
function addItem(data) {
    //userlist userid  ???
    var addSql = 'INSERT INTO friendarea(id,title,picurls) VALUES(?,?,?)';
    var addSqlParams = [data.id, data.title, data.picurls];
    //增
   // connection.query(addSql, addSqlParams)

   
   const mypromise = new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
        if (err) {
            return reject(err);
        }
        connection.query(addSql, addSqlParams, (err, result) => {
            //释放连接
            // pool.releaseConnection(connection)
            if (err) {
                return reject(err);
            }
            resolve(result);
        });
//这么设置，能够解决卡死问题
        connection.release();
    });
});


    //更新缓存，

    //     ,function (err, result) {
    // connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
    //   if (error) throw error;
    //   console.log('The solution is: ', results[0].solution);
    // });

    // connection.end()

}

function updateItem(data) {
    //??  update where id=data.id
}


async function deleteItem(delid) {
    //??  update where id=data.id
    var delSql = 'delete from friendarea where id=?';
    var delSqlParams = [delid];
    //增
   // connection.query(delSql, delSqlParams)

    pool.getConnection((err, connection) => {
        if (err) {
            return reject(err);
        }
        connection.query(delSql, delSqlParams, (err, result) => {
            //释放连接
            // pool.releaseConnection(connection)
            if (err) {
                return reject(err);
            }
            resolve(result);
        });
//这么设置，能够解决卡死问题
        connection.release();
    });
    return 'del ok!!!'
}

async function getMoments() {

    // 先去缓存里查找，有的话，直接从缓存读取，没有的话，从数据库读取，再存到缓存以便下次请求时使用
    const sql = "select * from friendarea"

    const mypromise = new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                return reject(err);
            }
            connection.query(sql, (err, result) => {
                //释放连接
                // pool.releaseConnection(connection)
                if (err) {
                    return reject(err);
                }
                resolve(result);
            });
    //这么设置，能够解决卡死问题
            connection.release();
        });
      
    });

    const result = await mypromise
    const myarray = JSON.parse(JSON.stringify(result))   //RowDataPacket
    return myarray

    //存到缓存，后面从缓存里面获取
}

/*
async function addItem(data){

   const tlist=await getMoments()

   tlist.push(data)

   const jstr=JSON.stringify(tlist)
   const key="friendarea"
   client.set(key,jstr)
}*/


module.exports = {
    getMoments, addItem, deleteItem
}